package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"strconv"
	"strings"
	"time"

	"github.com/pkg/term"
)

func getch(t *term.Term) []byte {
	bytes := make([]byte, 1)
	_, err := t.Read(bytes)
	if err != nil {
		return nil
	}
	return bytes[:]
}

func main() {
	var recvBefore [10]float64
	var transBefore [10]float64
	var netcard string
	t, _ := term.Open("/dev/tty")
	term.CBreakMode(t)

	go func() {
		for {
			c := getch(t)
			if c == nil {
				log.Println("getch error")
				os.Exit(2)
			}
			if c[0] == 'q' {
				os.Exit(0)
			}
		}
	}()
	flag.StringVar(&netcard, "i", "all", "-i eno1")
	flag.Parse()
	for {
		select {
		case <-time.After(time.Second):
			netdata, err := ioutil.ReadFile("/proc/net/dev")
			if err != nil {
				log.Fatalln("Can't open the file")
				os.Exit(1)
			}
			lines := strings.Split(string(netdata), "\n")
			fmt.Println("\033c")
			fmt.Println("实时网速:")
			for i := 2; i < len(lines)-1; i++ {
				splitdata := strings.Split(lines[i], ":")
				dev := splitdata[0]
				if netcard == strings.Fields(dev)[0] || netcard == "all" {
					transdata := strings.Fields(splitdata[1])
					recv_byte := transdata[0]
					trans_byte := transdata[8]
					recv, _ := strconv.ParseFloat(recv_byte, 64)
					trans, _ := strconv.ParseFloat(trans_byte, 64)
					//fmt.Printf("%d   %d",recvBefore,transBefore)
					Rx := (recv - recvBefore[i]) / 1 / 1024
					Tx := (trans - transBefore[i]) / 1 / 1024
					if Rx > 1024 && Tx > 1024 {
						fmt.Printf("%s: Down: %f MB, Up:%f MB,Total:%f GB\n", dev, Rx/1024, Tx/1024, float64(recv/1024.0/1024.0/1024.0))
					} else if Rx > 1024 && Tx < 1024 {
						fmt.Printf("%s: Down: %f MB, Up:%f KB,Total:%f GB\n", dev, Rx/1024, Tx, float64(recv/1024.0/1024.0/1024.0))
					} else if Rx < 1024 && Tx > 1024 {
						fmt.Printf("%s: Down: %f KB, Up:%f MB,Total:%f GB\n", dev, Rx, Tx/1024, float64(recv/1024.0/1024.0/1024.0))
					} else if Rx < 1024 && Tx < 1024 {
						fmt.Printf("%s: Down: %f KB, Up:%f KB,Total:%f GB\n", dev, Rx/1024, Tx/1024, float64(recv/1024.0/1024.0/1024.0))
					}

					recvBefore[i] = recv
					transBefore[i] = trans
				}
			}
		}
	}

}
